package cn.dw.mm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.zip.ZipInputStream;

import org.activiti.engine.repository.DeploymentBuilder;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 部署流程
 *
 * @author Jinguang
 */
@Controller
@RequestMapping(value = "/activiti/deploy")
public class DeploymentController extends ActivitiAbstractController {
	
	/**
     * 线上部署流程资源
     */
    @RequestMapping(value = "/deployOnline")
    public String deploy(@RequestParam(value = "file", required = true) MultipartFile file) {

        // 获取上传的文件名
        String fileName = file.getOriginalFilename();

        try {
            // 得到输入流（字节流）对象
            InputStream fileInputStream = file.getInputStream();

            // 文件的扩展名
            String extension = FilenameUtils.getExtension(fileName);

            // zip或者bar类型的文件用ZipInputStream方式部署
            DeploymentBuilder deployment = repositoryService.createDeployment();
            if (extension.equals("zip") || extension.equals("bar")) {
                ZipInputStream zip = new ZipInputStream(fileInputStream);
                deployment.addZipInputStream(zip);
            } else {
                // 其他类型的文件直接部署
                deployment.addInputStream(fileName, fileInputStream);
            }
            deployment.deploy();
        } catch (Exception e) {
            logger.error("error on deploy process, because of file input stream");
        }

        return "redirect:process-list";
    }
    
    /**
     * 部署本地资源
     */
    @RequestMapping(value = "/deployLocal")
    @ResponseBody
    public String deployLocal(@RequestParam("bpmnName") String bpmnName) {
    	File file = new File(this.getClass().getClassLoader().getResource(bpmnName).getPath());
    	try {
			FileInputStream fileInputStream = new FileInputStream(file);
			DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
			deploymentBuilder.addInputStream(bpmnName, fileInputStream);
			deploymentBuilder.deploy();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    	return "Success";
    }
    
    
   

}
